// WebSocket服务类
class WebSocketService {
  constructor() {
    this.ws = null;
    this.reconnectInterval = 5000; // 重连间隔(ms)
    this.maxReconnectAttempts = 10; // 最大重连次数
    this.reconnectAttempts = 0; // 当前重连次数
    this.isManualClose = false; // 是否手动关闭连接
    this.url = 'ws://localhost:8080/ws/device-status'; // WebSocket服务器地址
    this.callbacks = {}; // 事件回调函数
  }

  // 连接WebSocket服务器
  connect() {
    try {
      this.ws = new WebSocket(this.url);
      this.isManualClose = false;
      this.reconnectAttempts = 0;

      // 连接成功事件
      this.ws.onopen = (event) => {
        console.log('WebSocket连接成功:', event);
        this.reconnectAttempts = 0;
        this.emit('open', event);
      };

      // 接收消息事件
      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          this.emit('message', data);
          
          // 根据消息类型分发事件
          if (data.type) {
            this.emit(`message:${data.type}`, data);
          }
        } catch (error) {
          console.error('解析WebSocket消息失败:', error);
          this.emit('error', error);
        }
      };

      // 连接关闭事件
      this.ws.onclose = (event) => {
        console.log('WebSocket连接关闭:', event);
        this.emit('close', event);
        
        // 自动重连（如果不是手动关闭）
        if (!this.isManualClose && this.reconnectAttempts < this.maxReconnectAttempts) {
          this.scheduleReconnect();
        }
      };

      // 连接错误事件
      this.ws.onerror = (error) => {
        console.error('WebSocket连接错误:', error);
        this.emit('error', error);
      };

    } catch (error) {
      console.error('WebSocket连接异常:', error);
      this.emit('error', error);
      this.scheduleReconnect();
    }
  }

  // 发送消息到服务器
  send(message) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      try {
        const data = typeof message === 'object' ? JSON.stringify(message) : message;
        this.ws.send(data);
        return true;
      } catch (error) {
        console.error('发送WebSocket消息失败:', error);
        this.emit('error', error);
        return false;
      }
    } else {
      console.warn('WebSocket连接未建立，无法发送消息');
      return false;
    }
  }

  // 关闭WebSocket连接
  close() {
    this.isManualClose = true;
    if (this.ws) {
      this.ws.close();
    }
  }

  // 安排重连
  scheduleReconnect() {
    this.reconnectAttempts++;
    console.log(`计划在${this.reconnectInterval}ms后进行第${this.reconnectAttempts}次重连`);
    
    setTimeout(() => {
      this.connect();
    }, this.reconnectInterval);
  }

  // 注册事件监听
  on(event, callback) {
    if (!this.callbacks[event]) {
      this.callbacks[event] = [];
    }
    this.callbacks[event].push(callback);
  }

  // 移除事件监听
  off(event, callback) {
    if (this.callbacks[event]) {
      if (callback) {
        this.callbacks[event] = this.callbacks[event].filter(cb => cb !== callback);
      } else {
        delete this.callbacks[event];
      }
    }
  }

  // 触发事件
  emit(event, data) {
    if (this.callbacks[event]) {
      this.callbacks[event].forEach(callback => {
        try {
          callback(data);
        } catch (error) {
          console.error(`事件${event}处理失败:`, error);
        }
      });
    }
  }

  // 获取连接状态
  getReadyState() {
    if (!this.ws) {
      return WebSocket.CLOSED;
    }
    return this.ws.readyState;
  }

  // 检查连接是否打开
  isConnected() {
    return this.ws && this.ws.readyState === WebSocket.OPEN;
  }

  // 更新WebSocket服务器地址
  setUrl(newUrl) {
    this.url = newUrl;
    // 如果已经连接，重新连接到新地址
    if (this.isConnected()) {
      this.close();
      this.connect();
    }
  }
}

// 导出单例实例
export default new WebSocketService();